import { http } from "@/utils/http";
import { PureHttpResponse } from "@/utils/http/types";
import { ElLoading,ElMessage } from "element-plus";
import JSZip from 'jszip'
import FileSaver from 'file-saver'
// 下载全部文件
export const downloadAll = (fileList:any[]) => {
    const zip = new JSZip();
    const promises = [];
    //遍历文件地址
    fileList.forEach(item => {
      const promise = getfile(item).then(data => {
            let index = item.lastIndexOf("/");
            let filename = item.substring(
              index + 1,
              item.length
            );
            zip.file(filename, data.data, { binary: true })
        });
        promises.push(promise);
    });
    Promise.all(promises).then(() => {
        zip.generateAsync({ type: "blob" }).then(content => {
            // 生成二进制流
            FileSaver.saveAs(content, `123.zip`);
        });
    });
}
const getfile = (url: string, params?: any,method?: any,fileName?:any) => {
  return new Promise((resolve, reject) => {
    const loading = ElLoading.service({
    lock: true,
    text: "请稍后……",
    background: "rgba(0, 0, 0, 0.7)"
  });
  http
    .request(method ? method : "get", url, method ? {
      responseType: "blob",
       data: params
    } : {
      responseType: "blob",
      params
    })
    .then((response: PureHttpResponse) => {
      const { headers } = response;
      console.log(headers)
      const {
        "content-type": contentType,
        "content-disposition": contentDisposition
      } = headers;
      const blob = new Blob([response.data], {
        type: contentType
      });
      const pattern = new RegExp("filename*=([^;]+\\.[^\\.;]+);*");
      const result = pattern.exec(contentDisposition) as RegExpExecArray;
      // const filename = fileName ? fileName : decodeURI(result[1]); // 处理文件名,解决中文乱码问题
      resolve({data:blob})
    }).catch((error) => { 
      console.log(error)
    })
    .finally(() => {
      loading.close();
    });
  })
}
export const downloadFile = (url: string, params?: any,method?: any,fileName?:any) => {
  const loading = ElLoading.service({
    lock: true,
    text: "请稍后……",
    background: "rgba(0, 0, 0, 0.7)"
  });
  http
    .request(method ? method : "get", url, method ? {
      responseType: "blob",
       data: params
    } : {
      responseType: "blob",
      params
    })
    .then((response: PureHttpResponse) => {
      if (response.data.type == 'application/json') { 
        const fileReader = new FileReader()
        fileReader.onloadend = () => {
          const jsonData = JSON.parse(fileReader.result)
          // 后台信息
          console.log(jsonData)
          ElMessage.error(jsonData.msg);
        }
        fileReader.readAsText(response.data)
        return false;
      }
      const { headers } = response;
      const {
        "content-type": contentType,
        "content-disposition": contentDisposition
      } = headers;
      const blob = new Blob([response.data], {
        type: contentType
      });
      const pattern = new RegExp("filename*=([^;]+\\.[^\\.;]+);*");
      const result = pattern.exec(contentDisposition) as RegExpExecArray;
      console.log(123123,result)
      const filename = fileName ? fileName : decodeURI(result[1]); // 处理文件名,解决中文乱码问题
      const downloadElement = document.createElement("a");
      const href = window.URL.createObjectURL(blob); // 创建下载的链接
      downloadElement.style.display = "none";
      downloadElement.href = href;
      downloadElement.download = filename; // 下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
      window.URL.revokeObjectURL(href);
    }).catch((error) => { 
      console.log(error)
    })
    .finally(() => {
      loading.close();
    });
};
